package main

import (
	"fmt"
	"gitee.com/scottq/go-framework/src/miscs"
	v1 "gitee.com/scottq/go-framework/src/v1"
	v1http "gitee.com/scottq/go-framework/src/v1/httpserver"
	v1log "gitee.com/scottq/go-framework/src/v1/log"
	"os"
	"path/filepath"
	"time"
)

func main() {
	logPath := fmt.Sprintf("./runtime/logs/%s.log", filepath.Base(os.Args[0]))

	logger := v1log.NewZapLog("exampleApp", logPath, nil)

	server1 := getHttpServer(logger, ":8080")
	server2 := getHttpServer(logger, ":8083")
	app, err := v1.NewApp(
		"exampleApp",
		v1.WithAppOpsLog(logger),
		v1.WithAppOpsStopTimeout(time.Second*5),
		v1.WithAppOpsServer(server1),
		v1.WithAppOpsServer(server2),
	)
	if err != nil {
		logger.Fatal("new app error: " + err.Error())
		return
	}

	go func() {
		time.Sleep(time.Second * 3)
		logger.Info("stop server")
		//server1.Stop()

		app.Stop()
	}()

	err = app.Run()
	if err != nil {
		logger.Fatal("app running error: " + err.Error())
	}

}

func getHttpServer(logger v1log.ILog, addr string) *v1http.HttpServer {
	httpServer, err := v1http.NewHttpServer("exampleHttpServer", addr)
	if err != nil {
		logger.Error("run http server error:%s" + err.Error())
		panic(err)
	}
	httpServer.AddLogger(logger)
	httpServer.RouteGet("/v1", func(ctx *v1http.Ctx) {
		ctx.WriteStr("Hello World")
	}, []v1http.Middleware{})

	httpServer.RouteGet("/v1/panic", func(ctx *v1http.Ctx) {
		panic("trigger panic " + time.Now().Format(miscs.DateTimeLayout))
	}, []v1http.Middleware{})

	return httpServer
}
